import json

import requests
from fastapi import (APIRouter, Query, BackgroundTasks)

from config.application import profiles
from database.dbmanager import PgManager
from database.model import StatisticGraph, StatisticParameter
from entity.R import R

overall_process_router = APIRouter()




@overall_process_router.get("/test", tags=["总体流程"], summary="测试")
def test():
    return {"message": "Hello World"}


@overall_process_router.get("/getHistoryData", tags=["总体流程"], summary="获取计算结果")
def getHistoryData(time_stamp: str = Query(..., title="时间戳", description="时间戳")):
    """
    :param time_stamp:时间戳
    :return: 返回查询到的结果
    """
    try:
        pg_manager = PgManager(profiles["current"].postgres_config)
        with pg_manager.get_dbsession() as session:
            statisticGraph = session.query(StatisticGraph).filter(
                StatisticGraph.insert_time == time_stamp).first()
            if statisticGraph:
                return R.success(data=statisticGraph.json_data, message="ok")
            else:
                return R.error(message="未找到该记录")
    except Exception as e:
        return R.error(message=str(e))


@overall_process_router.get("/getHistoryAllRegion", tags=["总体流程"], summary="获取统计类型的所有区域")
def getHistoryAllRegion(time_stamp: str = Query(..., title="时间戳", description="时间戳")):
    """
    :param time_stamp:时间戳
    :return: 通过时间戳来获取所有区域的名字
    """
    # 查询StatistcGraph表中insert_time字段为time_stamp的，regin_name字段的distinct值
    try:
        pg_manager = PgManager(profiles["current"].postgres_config)
        with pg_manager.get_dbsession() as session:
            statisticGraph = session.query(StatisticGraph.region_name).filter(
                StatisticGraph.insert_time == time_stamp).distinct().all()
            # 返回的是一个列表，列表中的每个元素是查询到的regin_name的值,用列表推导式将其转化为列表
            result = {time_stamp: [i[0] for i in statisticGraph]}
            if statisticGraph:
                return R.success(data=result, message="ok")
            else:
                return R.error(message="未找到该记录")
    except Exception as e:
        return R.error(message=str(e))


@overall_process_router.get("/getGraphDataTimestampRegionname", tags=["总体流程"], summary="获取图表信息")
def getGraphDataTimestampRegionname(time_stamp: str = Query(..., title="时间戳", description="时间戳"),
                                    region_name: str = Query(default=..., title="区域名称", summary="区域名称")):
    """

    :param time_stamp:时间戳
    :param region_name: 地区的名字
    :return:
    """
    try:
        pg_manager = PgManager(profiles["current"].postgres_config)
        with pg_manager.get_dbsession() as session:
            statisticGraph = session.query(StatisticGraph).filter(
                StatisticGraph.insert_time == time_stamp, StatisticGraph.region_name == region_name).first()
            if statisticGraph:
                return R.success(data=statisticGraph.json_data, message="ok")
            else:
                return R.error(message="未找到该记录")
    except Exception as e:
        return R.error(message=str(e))


########################################################################################################################

#与包一接口交互：1修改人工修正插件状态 2获取参数  3保存参数
#通过页面的taskId来获取参数中的时间戳，然后通过时间戳来获取结果


@overall_process_router.get("/callback_ok", tags=["总体流程"], summary="更改人工修正插件状态")
def callback_ok(taskId: str = Query(..., title="任务id", description="任务id")):
    """_summary_
    Url：http://10.1.10.139:8021/setPlugSucceed
    请求方式：get
    请求参数： taskId  (任务id，类型String)
    返回类型：string
    描述：将人工修正插件状态修改为成功
    请求示例：
    http://10.1.10.139:8021/setPlugSucceed?taskId=33f5ccaa-dc6d-45fe-84c2-74ba2c6041e4

    """
    url = "http://10.1.10.139:8021/setPlugSucceed"
    params = {"taskId": taskId}
    try:
        response = requests.get(url=url, params=params)
        if response.status_code == 200:
            return R.success(data="ok", message="ok")
        else:
            return R.error(message="请求失败")
    except Exception as e:
        return R.error(message=str(e))


def save_parameters(taskId: str, parameters: str):
    try:
        pg_manager = PgManager(profiles["current"].postgres_config)
        with pg_manager.get_dbsession() as session:
            statisticParameter = StatisticParameter(taskId=taskId, parameter=parameters)
            session.add(statisticParameter)
    except Exception as e:
        print(e)


@overall_process_router.get("/get_parameters", tags=["总体流程"], summary="通过taskId获取参数")
def get_parameters(taskId: str = Query(..., title="任务id", description="任务id"),
                   background_tasks: BackgroundTasks = BackgroundTasks):
    """
     Url：http://10.1.10.139:8021/getParams
    请求方式：get
    请求参数： taskId  (任务id，类型String)
    返回类型：json
    描述：解析返回的json可以得到输入输出参数。
    请求示例：
    http://10.1.10.139:8021/getParams?taskId=33f5ccaa-dc6d-45fe-84c2-74ba2c6041e4
    """
    def get_remote_parameters(task_id):
        #url = "http://10.0.5.169:8021/getHumanParams"
        url = "http://10.1.10.139:8021/getParams"
        params = {"taskId": task_id}
        try:
            response = requests.get(url=url, params=params, timeout=5)  # 设置适当的超时时间
            response.raise_for_status()  # 检查HTTP响应状态
            return response.json()
        except requests.exceptions.RequestException as e:
            raise Exception(f"请求失败: {str(e)}")

    try:
        pg_manager = PgManager(profiles["current"].postgres_config)
        with pg_manager.get_dbsession() as session:
            statistic_parameter = session.query(StatisticParameter).filter(StatisticParameter.taskId == taskId).first()
            if statistic_parameter:
                return R.success(data=statistic_parameter.parameter, message="ok")
            remote_parameters = get_remote_parameters(taskId)
            background_tasks.add_task(save_parameters, taskId, remote_parameters)
            return R.success(data=remote_parameters, message="ok")
    except Exception as e:
        return R.error(message=str(e))
########################################################################################################################
